package com.wei.web.demo.user.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

@Slf4j
public class HandShakeInterceptor extends HttpSessionHandshakeInterceptor {

    /*
     * 在WebSocket连接建立之前的操作，以鉴权为例
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        log.info("beforeHandshake start validate");
        ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
        String token = serverRequest.getServletRequest().getParameter("token");
        log.info("beforeHandshake start validate. token: {}", token);
        if (("wei".equals(token))) {
            //此处将token传递到WebSocketController，必须写否则拿不到数据
            attributes.put("token", token + "123");
            return super.beforeHandshake(request, response, wsHandler, attributes);
        } else {
            return false;
        }
    }


    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception ex) {
        // 省略根据业务处理
    }
}
